<template>
  <Modal v-model="visible" width="750" :title="isEdit ? '上传订单附件' : '查看订单附件'"
    @on-visible-change="closeModal">
    <div class="order-files-content">
      <div class="download-btn" v-if="!isEdit && showDownload">
        <Button type="primary" @click="onDownload">下载附件</Button>
      </div>
      <div v-for="(item, index) in list" :key="item.attachType">
        <label
          :style="data.orderType == 1 ? 'width: 150px;' : 'width: 210px;'">{{ item.name }}:</label>
        <div>
          <!-- 已有附件 -->
          <template v-if="item.attachAddress.length">
            <div v-for="(file, i) in item.attachAddress" :key="i">
              <file-item :data="file" :show-delete="false" @preview="onPreview(item, i)" />
            </div>
          </template>
          <!-- 新上传附件 -->
          <template v-if="item.addAddress.length">
            <div v-for="(file, i) in item.addAddress" :key="'add' + i">
              <file-item :data="file" @remove="onRemove(i, index)"
                @preview="onPreview(item, item.attachAddress.length + i)" />
            </div>
          </template>
          <!-- 待补 -->
          <div v-if="!item.attachAddress.length && item.backupDate"
            class="no-img text-center flex flex-vertical-center flex-wrap">
            <p>待补</p>
            <p>{{ item.backupDate }}</p>
          </div>
          <!-- 上传 -->
          <Upload v-if="isShow(item)" ref="upload" name="multipartFile" multiple
            :action="upload.reqUrl" :headers="upload.headers" :data="upload.data"
            :show-upload-list="false" accept="image/png, image/jpg, image/jpeg"
            :before-upload="(file) => beforeUpload(file, index)"
            :on-success="(res, file, fileList) => onSuccess(res, file, fileList, index)"
            @click.native="onClick(item)"
            style="margin: 0 10px 10px 0;">
            <div
              style="width: 100px; height: 100px; line-height: 100px; text-align: center; border: 1px dashed #dadada; cursor: pointer;">
              <Icon type="ios-add" :size="30" />
            </div>
          </Upload>
        </div>
      </div>
    </div>
    <div slot="footer">
      <Button v-if="!isEdit" @click="onClose">关闭</Button>
      <Button v-if="isEdit" type="text" @click="onClose">取消</Button>
      <Button v-if="isEdit" type="primary" @click="onConfirm">确定</Button>
    </div>

    <preview-image ref="previewImage" :images="preview.images" :showDownLoad="true" :showIndex="preview.showIndex" />
  </Modal>
</template>

<script>
  import fileItem from './file-item.vue'
  import enclosureMgr from '@/biz/sales/enclosure.js'
  import toolMgr from '@/biz/base/tool.js'

  export default {
    props: {
      data: Object,
      isEdit: Boolean,
      nodeType: String,
    },
    components: {
      fileItem
    },
    data() {
      return {
        visible: false,
        list: [],
        upload: toolMgr.unloadImage(),
        preview: {
          images: [],
          showIndex: 0
        },
        showDownload: false,
        uploadNum: {
          num: null,
          flag: false
        },
        fileList: []
      }
    },
    methods: {
      onConfirm() {
        let arr = []
        for (let item of this.list) {
          if (item.addAddress.length) {
            arr.push({
              attachType: item.attachType,
              attachId: item.attachId,
              attachAddress: JSON.stringify([...item.attachAddress, ...item.addAddress]),
              addAddress: JSON.stringify(item.addAddress)
            })
          }
        }
        if (arr.length) {
          enclosureMgr.update({
            businessId: this.data.orderCode,
            orAnnexReqs: arr
          }).then(res => {
            this.$Message.success('上传成功')
            this.onClose()
            this.$emit('success')
          })
        } else {
          this.onClose()
        }
      },
      // 下载附件
      onDownload() {
        let module = ''
        switch (this.nodeType) {
          case '1':
            module = '案场列表-流程审批-渠道合规性审核';
            break;
          case '2':
            module = '流程中心-渠道合规性审核-子公司综管审核';
            break;
          case '3':
            module = '流程中心-渠道合规性审核-新房事业部审核';
            break;
          default:
            break;
        }
        toolMgr.downloadCenter(
          this.data.orderType == 1 ? '/dt-order/order/loadDownAttach' :
          '/dt-order/contract/loadContractAnnex',
          {
            housesId: this.$dt.buildInfo().housesId,
            orderCodeList: [this.data.orderCode],
            userId: this.$dt.userInfo().userId,
            module
          }
        )
      },
      onClick(item) {
        this.uploadNum.num = item.attachAddress.length + item.addAddress.length
      },
      beforeUpload(file, index) {
        this.uploadNum.num += 1
        if (this.uploadNum.num > 30) {
          !this.uploadNum.flag && this.$Message.error('最多上传30张图片')
          this.uploadNum.flag = true
          return false
        } else {
          return true
        }
      },
      // 上传成功
      onSuccess(res, file, fileList, index) {
        if (res.code == '200') {
          this.fileList.push(file)
          this.list[index].addAddress.push({
            url: res.data.imageURL,
            date: this.$tool.formatDate(new Date()),
          })
          if (this.fileList.length == fileList.length) {
            this.uploadNum.flag = false
            this.fileList = []
          }
        } else {
          this.$Message.error(res.msg)
        }
      },
      // 删除
      onRemove(fileIndex, index) {
        let addAddress = this.list[index].addAddress
        addAddress.splice(fileIndex, 1)
        this.list[index].addAddress = addAddress
      },
      onPreview(data, index) {
        let images = [...data.attachAddress, ...data.addAddress]
        this.preview.images = images.map(i => (i.url))
        this.preview.showIndex = index
        this.$refs.previewImage.show()
      },
      // 获取附件列表
      getEnclosure() {
        enclosureMgr.list(this.data.orderId, this.data.orderType).then(res => {
          this.list = res.map(i => ({
            ...i,
            attachAddress: i.attachAddress || [],
            addAddress: []
          }))
        })
      },
      isShow(item) {
        let num = item.attachAddress.length + item.addAddress.length
        return this.isEdit && num < 30
      },
      onClose() {
        this.visible = false
      },
      closeModal(res) {
        if (res) {
          this.getEnclosure()
          // 是否显示下载附件按钮
          if (this.data.orderType == 1) {
            this.showDownload = this.unlocking('0104010308')
          } else {
            this.showDownload = this.unlocking('0104030312')
          }
        }
      },
    },
  }
</script>

<style lang='scss' scoped>
  .order-files-content {
    max-height: calc(100vh - 300px);
    padding-top: 30px;
    overflow-y: auto;
    position: relative;

    >div {
      display: flex;
      margin-bottom: 20px;

      >label {
        text-align: right;
        margin-right: 10px;
      }

      >div {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
      }
    }
  }

  .no-img {
    color: #d9001b;
    width: 100px;
    height: 100px;
    border: 1px solid #dadada;
    margin: 0 10px 10px 0;

    p {
      width: 100%;
    }
  }

  .download-btn {
    position: absolute;
    top: 0;
    right: 0;
  }
</style>